package com.zzyweb.demomp.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Verification;
import com.zzyweb.demomp.entity.User;
import com.zzyweb.demomp.jwt.TokenEnum;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhiyi
 * @date 9/9/25
 **/

public class JWTUtil {
    private static final String SECRET_KEY = "zhiyizhang127101998";
    private static final String ISSUER = "Issuer";
    private static final long EXPIRE_TIME = 1000 * 60 * 60; // 单位是毫秒
    private static final Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
    public static String createAccessToken(User user) {
        Date now = new Date();
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", user.getUsername());
        claims.put("role", user.getRole().getName());
        claims.put("userId", user.getUserId());
        String token = JWT.create()
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + EXPIRE_TIME))
                .withClaim("userinfo", claims)
                .withIssuer(ISSUER)
                .sign(algorithm);
        return token;
    }

    public TokenEnum verifyToken(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            jwtVerifier.verify(token);
            return TokenEnum.VALIDTOKEN;
        } catch (JWTVerificationException e) {
            throw new RuntimeException(e);
        }
    }

   /* public String refreshToken(String token) {

    }*/
}
